package com.fishingwithme.android.ui.screens.map.screens

import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import com.fishingwithme.android.ui.screens.map.TencentMapWrapper
import java.util.UUID

@Composable
fun MapSelectionScreen(
    navController: NavController,
    moduleKey: String
) {
    val context = LocalContext.current
    val sessionId = remember { UUID.randomUUID().toString() }
    var permissionsGranted by remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        )
    }

    // 权限请求
    DisposableEffect(Unit) {
        val requiredPermissions = arrayOf(
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        val allGranted = requiredPermissions.all {
            ContextCompat.checkSelfPermission(
                context,
                it
            ) == PackageManager.PERMISSION_GRANTED
        }

        permissionsGranted = allGranted

        onDispose {
            Log.d("MapSelectionScreen", "屏幕销毁，会话ID: $sessionId")
        }
    }

    // 只显示TencentMapWrapper组件
    val mapData = remember { mutableMapOf<String, Any>("sessionId" to sessionId) }

    TencentMapWrapper(
        modifier = Modifier.fillMaxSize(),
        permissionsGranted = permissionsGranted,
        moduleKey = moduleKey,
        data = mapData,
        onNavigateBack = {
            // Navigate back to the AddSpotScreen without recreating it
            navController.popBackStack()
        }
    )
}